import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_rider/event/new_order_event.dart';
import 'package:flutter_rider/event/refresh_order_event.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/module/task/task_router.dart';
import 'package:flutter_rider/routers/fluro_navigator.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/state/refreshable_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';

class TaskPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return TaskPageState();
  }
}

class TaskPageState extends State<TaskPage> {
  final _stateController = RefreshableLayoutController();
  final _inputController = TextEditingController(text: "");
  late StreamSubscription _eventFn;
  // late StreamSubscription _eventFn2;
  List _tabs = ["待装货", "待卸货", "已完成", "已取消"];
  bool _showUndistributed = false;
  String _lx = "全部任务";
  int _index = 0;
  // 全部任务：0   我的任务：1
  int _lxIndex = 0;
  // 全部任务 ，我的任务蒙层
  bool _showLxDialog = false;

  @override
  void initState() {
    super.initState();
    _eventFn = eventBus.on<RefreshOrderEvent>().listen((event) {
      _stateController.reload();
    });
    // _eventFn2 = eventBus.on<NewOrderEvent>().listen((event) {
    //   _stateController.reload();
    // });
    _stateController.reload();
    initButton();

  }

  @override
  void dispose() {
    super.dispose();
    _eventFn.cancel();
    // _eventFn2.cancel();
    _inputController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
        color: UIColor.color_main,
        child: Stack(
            children: [
                Column(children: [
                    _renderTitle(),
                    _renderInput(),
                    _renderTab(),
                    Container(height: 0.5, color: Colors.black12),
                    _renderList(),
                ],

            ),
            _showLxDialog? _renderLx() : 0.wspace,
            _showLxDialog?_renderLxContent() : 0.wspace
          ],
        )
    );
  }

  String _buildUrl() {
    int status = _showUndistributed ? 99 : 1;
    if (_tabs[_index] == '待装货') {
      status = 1;
    } else if (_tabs[_index] == '待卸货') {
      status = 2;
    } else if (_tabs[_index] == '已完成') {
      status = 5;
    } else if (_tabs[_index] == '已取消') {
      status = 20;
    }
    var baseUrl = "/waybill_mission/list?status=$status&mine=$_lxIndex";
    var searchKey = _inputController.text.trim();
    if (searchKey.isNotEmpty) {
      if (!baseUrl.contains("?")) {
        baseUrl += "?";
      } else {
        baseUrl += "&";
      }
      baseUrl += "search_key=${Uri.encodeComponent(searchKey)}";
    }
    return baseUrl;
  }

  Widget _renderList() {
    return Expanded(
        child: RefreshableLayout(
            controller: _stateController,
            urlCallback: _buildUrl,
            itemBuilder: _renderListItem));
  }

  Widget _renderListItem(dynamic data, int index) {
    return GestureDetector(
      onTap: () {
        NavigatorUtils.push(context, TaskRouter.taskDetailPage,
            arguments: data["id"].toString());
      },
      child: Container(
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        margin: EdgeInsets.only(top: 10.rpx),
        child: Column(
          children: [
            8.hspace,
            _renderItemTop(data),
            10.hspace,
            Container(height: 0.5.rpx, color: UIColor.color_divider),
            10.hspace,
            _renderSendAndRecv(data),
            data['status'] != 0 ? _renderCar(data) : 0.wspace,
            10.hspace,
            Container(height: 0.5.rpx, color: UIColor.color_divider),
            10.hspace,
            _renderTime(data),
            10.hspace,
          ],
        ),
      ),
    );
  }

  Widget _renderCar(dynamic data) {
    return Container(
        margin: EdgeInsets.only(top: 10.rpx),
        child: Row(
          children: [
            16.wspace,
            UText.get("履约车辆", UIColor.color_t7, 14.rpx).expand,
            UText.get("${data["car_no"]}", UIColor.color_primary, 14.rpx),
            16.wspace,
          ],
        ));
  }

  Widget _renderTime(dynamic data) {
    return Row(
      children: [
        16.wspace,
        UText.get(
                "下单时间: " + data["order_created_time"], UIColor.color_t8, 14.rpx)
            .expand,
        16.wspace,
      ],
    );
  }

  Widget _renderItemTop(dynamic data) {
    var st = data["operation"];
    dynamic widget, bgColor, color, name;
    if (st == 0) {
      bgColor = UIColor.color_t12;
      color = UIColor.color_t13;
      name = "未分配";
    } else if (st == 1) {
      bgColor = const Color(0xffED7B2F);
      color = UIColor.color_content;
      name = "待揽收";
    } else if (st == 2) {
      bgColor = const Color(0xff00A870);
      color = UIColor.color_content;
      name = data["mission_status"] < 7? "运输中" :"已到站"; // 运输中  已到站
    } else if (st == 3) {
      bgColor = UIColor.color_input;
      color = UIColor.color_t9;
      name = "已完成";
    } else if (st == -1) {
      bgColor = UIColor.color_input;
      color = UIColor.color_t7;
      name = "已取消";
    } else {
      return widget = 0.wspace;
    }
    widget = Container(
      width: 66.rpx,
      height: 32.rpx,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(60), bottomLeft: Radius.circular(60)),
      ),
      child: UText.get(name, color, 14.rpx),
    );
    return Row(
      children: [
        16.wspace,
        Expanded(
            child: Row(children: [
              UText.get("任务编号：${data["no"]}", UIColor.color_t3, 13.5.rpx),
              4.wspace,
              GestureDetector(
                onTap: () {
                  Clipboard.setData(ClipboardData(text: data["no"]));
                  Tip.show("已复制到剪贴板");
                },
                child: Container(
                  margin: EdgeInsets.only(top: 2.rpx),
                  child: SvgPicture.asset(
                    R.image_text_copy,
                    width: 16.rpx,
                    height: 16.rpx,
                  ),
                )
              ),
            ])
        ),
        widget,
      ],
    );
  }

  Widget _renderSendAndRecv(dynamic data) {
    return Row(
      children: [
        16.wspace,
        _renderSendCard(data),
        4.wspace,
        _renderArrow(),
        4.wspace,
        _renderRecvCard(data),
        16.wspace,
      ],
    );
  }

  Widget _renderArrow() {
    return ConstrainedBox(
      constraints: BoxConstraints(
        maxWidth: 20.rpx,
      ),
      child: Row(
        children: [
          Expanded(child: Divider(color: UIColor.color_divider, height: 0.5.rpx)),
          SvgPicture.asset(R.image_line_arrow_right,
              width: 5.rpx, height: 5.rpx, color: UIColor.color_divider),
        ],
      ),
    );
  }

  Widget _renderSendCard(dynamic data) {
    return Container(
      width: 160.rpx,
      height: 64.rpx,
      decoration: BoxDecoration(
        color: UIColor.color_input,
        borderRadius: BorderRadius.circular(8.rpx),
      ),
      child: Row(
        children: [
          10.wspace,
          SvgPicture.asset(R.image_send, width: 24.rpx, height: 24.rpx),
          6.wspace,
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                UText.get(data["pick_username"], UIColor.color_t1, 16.rpx,
                    overflow: TextOverflow.ellipsis),
                5.hspace,
                UText.get(data["pick_address"], UIColor.color_t5, 12.rpx,
                    overflow: TextOverflow.ellipsis),
              ],
            ),
          ),
        ],
      ),
    ).expand;
  }

  Widget _renderRecvCard(dynamic data) {
    return Container(
      width: 160.rpx,
      height: 64.rpx,
      decoration: BoxDecoration(
        color: UIColor.color_input,
        borderRadius: BorderRadius.all(Radius.circular(8.rpx)),
      ),
      child: Row(
        children: [
          10.wspace,
          SvgPicture.asset(R.image_get, width: 24.rpx, height: 24.rpx),
          6.wspace,
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                UText.get(data["delivery_username"], UIColor.color_t1, 16.rpx,
                    overflow: TextOverflow.ellipsis),
                5.hspace,
                UText.get(data["delivery_address"], UIColor.color_t5, 12.rpx,
                    overflow: TextOverflow.ellipsis),
              ],
            ),
          ),
        ],
      ),
    ).expand;
  }

  Widget _renderTitle() {
    return Container(
      color: UIColor.color_content,
      width: double.infinity,
      height: MediaQuery.of(context).padding.top + 44.rpx,
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      child: Center(
          child: UText.get("任务中心", Colors.black, 16.rpx, fw: FontWeight.w600)),
    );
  }

  Widget _renderInput() {
    return Container(
      color: UIColor.color_content,
      padding: EdgeInsets.symmetric(vertical: 4.rpx, horizontal: 16.rpx),
      child: Row(
          children: [
            GestureDetector(
              onTap: (){
                print("全部任务");
                setState(() {
                  _showLxDialog = true;
                });
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  UText.get(_lx, UIColor.color_t10, 14.rpx),
                  4.wspace,
                  SvgPicture.asset( _showLxDialog?R.image_arrows_up:R.image_arrows_down, width: 12.rpx, height: 12.rpx),
                  10.wspace,
                ],
              ),
            ),
            Expanded(
              child: TextField(
                controller: _inputController,
                style: TextStyle(color: UIColor.color_t1, fontSize: 14.rpx),
                textInputAction: TextInputAction.search,
                maxLength: 30,
                onEditingComplete: () {
                  _stateController.reload();
                },
                decoration: InputDecoration(
                    counterText: "",
                    contentPadding:
                    EdgeInsets.symmetric(vertical: 8.rpx, horizontal: 12.rpx),
                    isCollapsed: true,
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(
                          Radius.circular(20.rpx)
                        ),
                        borderSide: BorderSide.none
                    ),
                    prefixIcon: Padding(
                      padding: EdgeInsets.only(left: 10.rpx, right: 4.rpx, top: 3.rpx),
                      child: Icon(
                        Icons.search,
                        size: 18.rpx,
                        color: Colors.black.withOpacity(0.4),
                      ),
                    ),
                    prefixIconConstraints: BoxConstraints(maxHeight: 22.rpx),
                    hintText: "请输入任务编号、车辆编号",
                    hintStyle: TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 14.rpx),
                    filled: true,
                    fillColor: UIColor.color_input
                )
              ),
            )
          ]
      )
    );
  }

  FocusNode focusNode = FocusNode();
  OverlayEntry? overlayEntry;
  LayerLink layerLink = LayerLink();

  Widget _renderLx() {
    return GestureDetector(
      onTap: (){
        setState(() {
          _showLxDialog = false;
        });
      },
      child:Container(
          width: double.infinity,
          height: 900.rpx,
          margin: EdgeInsets.only(top:Platform.isIOS?150.rpx:120.rpx),
          color: UIColor.color_t4
      )
    );
  }

  Widget _renderLxContent() {
    return Container(
      width: 107.rpx,
      height: 103.rpx,
      margin: EdgeInsets.only(top: 120.rpx,left: 16.rpx),
      padding: EdgeInsets.symmetric(horizontal: 16.rpx),
      decoration:  const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/image/poi/bubble.png'),
          // fit: BoxFit.fill, // 完全填充
        ),
      ),
      child: Column(
        children: [
          GestureDetector(
            onTap: (){
              setState((){
                _lxIndex = 0;
                _showLxDialog = false;
                _lx = "全部任务";
              });
              _stateController.reload();
            },
            child: Container(
              padding: EdgeInsets.only(top: 20.rpx,bottom: 11.rpx),
              child: UText.get("全部任务", _lxIndex == 0?UIColor.color_primary:UIColor.color_t5, 16.rpx),
            )
          ),
          Container(height: 0.5, color: Colors.black12),
          GestureDetector(
            onTap: (){
              setState((){
                _lxIndex = 1;
                _showLxDialog = false;
                _lx = "我的任务";
              });
              _stateController.reload();
            },
            child: Container(
              padding: EdgeInsets.only(top: 14.rpx,bottom: 11.rpx),
              child: UText.get("我的任务", _lxIndex == 1?UIColor.color_primary:UIColor.color_t5, 16.rpx),
            )
          )
        ],
      ),
    );
  }

  Widget _renderTab() {
    return Container(
      color: UIColor.color_content,
      child: Row(
        children: _tabs.asMap().keys.map((e) => _renderTabItem(e)).toList(),
      )
    );
  }

  Widget _renderTabItem(int index) {
    var color =
        _index == index ? UIColor.color_primary : Colors.black.withOpacity(0.6);
    return Expanded(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          setState(() {
            _index = index;
            _stateController.reload();
          });
        },
        child: Column(
          children: [
            12.hspace,
            UText.get(_tabs[index], color, 16.rpx, fw: FontWeight.w600),
            3.hspace,
            Container(
              width: 24.rpx,
              height: 4.rpx,
              decoration: BoxDecoration(
                color: _index == index
                    ? UIColor.color_primary
                    : Colors.transparent,
                borderRadius: BorderRadius.all(Radius.circular(3.rpx)),
              ),
            ),
            3.hspace,
          ],
        ),
      ),
    );
  }

  initButton() async {
    var _sp = await SharedPreferences.getInstance();
    _showUndistributed = _sp.getBool("_showUndistributed") as bool;
    print(_showUndistributed);
    setState(() {
      _tabs = _showUndistributed
          ? ["未分配", "待装货", "待卸货", "已完成", "已取消"]
          : ["待装货", "待卸货", "已完成", "已取消"];
    });
  }
}
